package com.example.a2032.activity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.a2032.R;
import com.example.a2032.Utils.BleSdk;
import com.example.a2032.Utils.DateUtils;
import com.example.a2032.Utils.SchedulersTransformer;
import com.example.a2032.Utils.Utils;
import com.example.a2032.Utils.WebSocketUtils;
import com.example.a2032.db.DataDbHelper;
import com.example.a2032.entity.HeartRateData;
import com.example.a2032.entity.PPGMeasureData;
import com.example.a2032.net.jstylenet.JstyleConst;
import com.example.a2032.net.jstylenet.NetSendUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public class HeartRateMeasureActivity extends BaseActivity {

    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.iv_meausre_ready)
    ImageView ivMeausreReady;
    @BindView(R.id.tv_measure_tips1)
    TextView tvMeasureTips1;
    @BindView(R.id.tv_hrValue)
    TextView tvHrValue;
    @BindView(R.id.iv_meausre_tips)
    ImageView ivMeausreTips;
    @BindView(R.id.tv_measure_tips2)
    TextView tvMeasureTips2;
    @BindView(R.id.ll_measureTips)
    LinearLayout llMeasureTips;
    private Disposable disposableMeasureTips;
    int maxMeasureTime = 3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        KeepScreenOn();
        setContentView(R.layout.activity_heart_rate_measure);
        ButterKnife.bind(this);
        init();
    }

    String from = "";
    int currentHeart;

    private void init() {
        maxMeasureTime = getIntent().getIntExtra(KEY_MeasureTime, 3);
        from = getIntent().getStringExtra(KEY_MeasureFrom);
        if (maxMeasureTime == 0) maxMeasureTime = 1;
        subscribe(this);
        startTimer();
        boolean isMeasure = WebSocketUtils.getInstance().isMeasuring();
        tvHrValue.postDelayed(new Runnable() {
            @Override
            public void run() {
                sendData(BleSdk.enableHeartMeasure(true, maxMeasureTime));
            }
        }, isMeasure ? 1000 : 0);

        Glide.with(this).asGif().load(R.mipmap.mearure_hr).into(ivMeausreReady);
        ivMeausreTips.setImageResource(R.drawable.heart_offtips);

    }

    boolean isMeasureResult;

    private void showHrValue(int hr) {
        tvMeasureTips1.setText(hr == 0 ? R.string.measureing : R.string.realTime_hrValue);
        if (hr != 0 && !isMeasureResult) {//测量出来结果震动一次
            isMeasureResult = true;
            Utils.startVibrato(this);
        }
        tvHrValue.setText(hr == 0 ? "--" : String.valueOf(hr));

    }

    @OnClick(R.id.iv_back)
    public void onViewClicked() {
        finish();
    }

    long saveTime;

    @Override
    public void PPGMeasureData(PPGMeasureData ppgMeasureData) {
        super.PPGMeasureData(ppgMeasureData);
        int type = ppgMeasureData.getDataType();
        if (type == PPGMeasureData.MeasureData_PPGHR) {
            int state = ppgMeasureData.getWearStatus();
            if (state == PPGMeasureData.MeasureStatus_WearOff) {
                llMeasureTips.setVisibility(View.VISIBLE);
                upLoadData(0, JstyleConst.Measure_WearOff);
            } else {
                llMeasureTips.setVisibility(View.GONE);
                showMeasureData(ppgMeasureData);
            }

        }
    }

    private void showMeasureData(PPGMeasureData ppgMeasureData) {
        int heartRate = ppgMeasureData.getHeartRate();
        if (heartRate != 0) {
            HeartRateData heartRateData = new HeartRateData();
            heartRateData.setDataMode(0);
            heartRateData.setHeartRate(heartRate);
            heartRateData.setTime(getTime());
            //DemoDbHelper.getInstance(this).getHeartRateDao().insert(heartRateData);
            if (saveTime == 0 || System.currentTimeMillis() - saveTime > 60000) {
                //第一次测量出来值保存一次，后面每分钟保存一次
                Utils.saveBPData(this, ppgMeasureData, from);
                saveTime = System.currentTimeMillis();
            }
            currentHeart = heartRate;
            upLoadData(heartRate, JstyleConst.Measure_Progress);
        }
        showHrValue(heartRate);
    }

    void saveBPData(PPGMeasureData ppgMeasureData) {
        String date = DateUtils.getDefaultDate(new Date());
        ppgMeasureData.setDate(date);
        DataDbHelper.getInstance(this).getPPGDataDao().insert(ppgMeasureData);
    }

    void upLoadData(int hr, int state) {
        // if(isFinishing())return;
        String msg = NetSendUtils.realTimeHrData(hr, state, from);
        WebSocketUtils.getInstance().sendMsg(msg);
    }

    private String getTime() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy.MM.dd HH:mm");
        return simpleDateFormat.format(new Date());
    }

    private static final String TAG = "HeartRateMeasureActivit";

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.i(TAG, "onDestroy: ");
        sendData(BleSdk.enableHeartMeasure(false, maxMeasureTime));
        unSubscribe(disposableMeasureTips);
        upLoadData(currentHeart, JstyleConst.Measure_Finish);
        KeepScreenOff();
    }

    void startTimer() {
        Observable.timer(maxMeasureTime, TimeUnit.MINUTES).compose(SchedulersTransformer.io2MainObservable()).subscribe(new Observer<Long>() {
            @Override
            public void onSubscribe(Disposable d) {
                disposableMeasureTips = d;
            }

            @Override
            public void onNext(Long aLong) {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {
                //upLoadData(currentHeart, JstyleConst.Measure_Finish);
                finish();
            }
        });
    }

    @Override
    protected void stopMeasure() {
        super.stopMeasure();
        finish();
    }
}